package com.crtf.cmall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crtf.cmall.common.utils.PageUtils;
import com.crtf.cmall.common.utils.Query;

import com.crtf.cmall.product.dao.CategoryDao;
import com.crtf.cmall.product.entity.CategoryEntity;
import com.crtf.cmall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listwithTree() {
        // 1.查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
        // 2.组装成父子的树形结构
        // 2.1
        return entities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .peek(menu -> menu.setChildren(getChildrens(menu,entities)))
                .sorted(Comparator.comparingInt(menu2 -> (Objects.nonNull(menu2.getSort()) ? menu2.getSort() : 0)))
                .collect(Collectors.toList());
    }

    /**
     * 递归查找所有菜单的子菜单
     * @param menu 子菜单
     * @param entities 所有菜单
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity menu, List<CategoryEntity> entities){
        return entities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(menu.getCatId()))
                // 找到子菜单
                .peek(categoryEntity -> categoryEntity.setChildren(getChildrens(categoryEntity, entities)))
                // 排序
                .sorted(Comparator.comparingInt(menu2 -> (Objects.nonNull(menu2.getSort()) ? menu2.getSort() : 0)))
                .collect(Collectors.toList());
    }
}